package headfirst.combined.djview;

import java.util.*;


public class RPMModel implements RPMModelInterface{
	  	
		Motor motor;
		ArrayList beatObservers = new ArrayList();
		ArrayList rpmObservers = new ArrayList();
		ArrayList bpmObservers = new ArrayList();
	
		public void initialize() {
			motor = Motor.getInstance();
			//on();
		}
	 
	    public void on() {
	        if (motor.get_rpm()==0){
	        	for(int i=0; i<100; i++){
		    		motor.set_rpm(motor.get_rpm()+10);
		    		try {
						Thread.sleep(10);
					} catch (Exception e) {};
					notifyBPMObservers();
					notifyRPMObservers();
		    	}
	        }
	    }
	 
	    public void off() {
	    	while (motor.get_rpm()!=0){
	    		desacelerar();
	    	}
	    }
	    
	    public void acelerar() {
	    	for(int i=0; i<10; i++){
	    		motor.set_rpm(motor.get_rpm()+10);
	    		notifyBPMObservers();
				notifyRPMObservers();
	    		try {
					Thread.sleep(10);
				} catch (Exception e) {};
	    	}
	    }
	    
	    public void desacelerar() {
	    	for(int i=0; i<10; i++){
	    		motor.set_rpm(motor.get_rpm()-10);
	    		notifyBPMObservers();
				notifyRPMObservers();
	    		try {
					Thread.sleep(10);
				} catch (Exception e) {};
	    	}
	    }
	    
	    public boolean pruebaMotor1(){
	    	//Todavia no se implemento
	    	return false;
	    }
	    
	    public boolean pruebaMotor2(){
	    	//todavia no se implemento
	    	return false;
	    }
	    
		public int getRPM() {
			return motor.get_rpm();
		}
		
		public void registerObserver(BeatObserver o) {
			beatObservers.add(o);
		}

		public void removeObserver(BeatObserver o) {
			int i = beatObservers.indexOf(o);
			if (i >= 0) {
				beatObservers.remove(i);
			}
		}

		public void notifyBeatObservers() {
			for(int i = 0; i < beatObservers.size(); i++) {
				BeatObserver observer = (BeatObserver)beatObservers.get(i);
				observer.updateBeat();
			}
		}
		
		public void registerObserver(RPMObserver o) {
			rpmObservers.add(o);
		}
	  
		public void notifyRPMObservers() {
			for(int i = 0; i < rpmObservers.size(); i++) {
				RPMObserver observer = (RPMObserver)rpmObservers.get(i);
				observer.updateStress();
			}
		}
		
		
	  
		public void registerObserver(BPMObserver o) {
			bpmObservers.add(o);
		}
	  
		public void notifyBPMObservers() {
			for(int i = 0; i < bpmObservers.size(); i++) {
				BPMObserver observer = (BPMObserver)bpmObservers.get(i);
				observer.updateBPM();
			}
		}


		public void removeObserver(RPMObserver o) {
			int i = rpmObservers.indexOf(o);
			if (i >= 0) {
				rpmObservers.remove(i);
			}
		}

		public void removeObserver(BPMObserver o) {
			int i = bpmObservers.indexOf(o);
			if (i >= 0) {
				bpmObservers.remove(i);
			}
		}
} 
	


